package com.study_platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study_platform.entity.User;
import com.study_platform.mapper.UserMapper;
import com.study_platform.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study_platform.service.impl.utils.UserDetailsImpl;
import com.study_platform.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author auto
 * @since 2023-04-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public JSONObject getInfo() {
        JSONObject jsonObject = new JSONObject();
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();
        user.setPassword(null);
        jsonObject.put("user", user);
        jsonObject.put("error_message", "success");
        return jsonObject;
    }

    @Override
    public JSONObject register(Map<String, String> data) {
        JSONObject jsonObject = new JSONObject();
        String username = data.get("username");
        String password = data.get("password");
        String confirmedPassword = data.get("confirmedPassword");
        Integer age = Integer.valueOf(data.get("age"));
        String phone = data.get("phone");

        if (username == null) {
            jsonObject.put("error_message", "用户名不能为空");
            return jsonObject;
        }
        if (password == null || confirmedPassword == null) {
            jsonObject.put("error_message", "密码不能为空");
            return jsonObject;
        }

        username = username.trim();
        if (username.length() == 0) {
            jsonObject.put("error_message", "用户名不能为空");
            return jsonObject;
        }

        if (password.length() == 0 || confirmedPassword.length() == 0) {
            jsonObject.put("error_message", "密码不能为空");
            return jsonObject;
        }

        if (username.length() > 100) {
            jsonObject.put("error_message", "用户名长度不能大于100");
            return jsonObject;
        }

        if (password.length() > 100 || confirmedPassword.length() > 100) {
            jsonObject.put("error_message", "密码长度不能大于100");
            return jsonObject;
        }

        if (!password.equals(confirmedPassword)) {
            jsonObject.put("error_message", "两次输入的密码不一致");
            return jsonObject;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        User user = userMapper.selectOne(queryWrapper);
        if (null != user){
            jsonObject.put("error_message", "用户名已存在");
            return jsonObject;
        }

        String encodedPassword = passwordEncoder.encode(password);
        userMapper.insert(new User(null, username, encodedPassword, age, phone));
        jsonObject.put("error_message", "success");

        return jsonObject;
    }

    @Override
    public JSONObject login(Map<String, String> data) {
        JSONObject jsonObject = new JSONObject();
        String username = data.get("username");
        String password = data.get("password");

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getUserId().toString());

        jsonObject.put("error_message", "success");
        jsonObject.put("token", jwt);

        return jsonObject;
    }
}
